'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {

  postSned(code, msg, token = undefined) {
    return {
      code,
      msg,
      token,
    };
  }

  async get() {
    const { app, ctx } = this;
    try {
      const { userName } = app.jwt.verify(ctx.request.header.authorization.slice(7));
      const allUser = await this.app.mysql.select('users');
      const users = allUser.filter(users => users.userName !== userName);
      ctx.body = users;
    } catch (error) {
      ctx.body = {
        code: 50012,
        msg: error.message,
      };
    }

  }

  async getUserInfo() {
    const { ctx } = this;
  }

  async getUserById() {
    const { ctx } = this;
    const data = await this.app.mysql.get('users', { id: ctx.params.id });
    ctx.body = {
      code: 200,
      data,
      msg: '获取成功',
    };
  }

  async post() {
    const { ctx } = this;
    const { userName } = ctx.request.body;
    const isUserName = await this.app.mysql.get('users', { userName });
    let log;
    if (isUserName) {
      log = this.postSned(201, '用户名已存在');
    } else {
      const data = await this.app.mysql.insert('users', ctx.request.body);
      log = this.postSned(200, data.protocol41 ? '成功' : '失败');
    }
    ctx.body = log;
  }


  async login() {
    const { ctx, app } = this;
    const { userName, passWord } = ctx.request.body;
    const user = await app.mysql.get('users', { userName });

    if (user && user.passWord === passWord) {
      const token = app.jwt.sign({
        userName,
      }, app.config.jwt.secret);

      await app.redis.set(userName, token);

      ctx.body = this.postSned(200, 'success', token);
    } else {
      ctx.body = this.postSned(201, '用户名和密码不符');
    }

  }


}

module.exports = UserController;
